// 餐馆文件，主要是窗口的操作
#include <stdio.h>
#include <string.h>
#include "struct.h"
#include "restaurant.h"


// 0. 初始化餐馆
void Restaurant_init(Restaurant * pR){
	if(pR == NULL)	return;
	FILE* fp = fopen("./file.txt", "rb");
    if (!fp) {
        perror("加载文件失败");
        return;
    }
    // 读取餐馆名称
    int nameLen;
    int num = fread(&nameLen, sizeof(int), 1, fp);
	if (num != 1) { 
		// 如果读出的数不为1说明文件为空，那就赋初值
		strncpy(pR->restaurant_name, "未命名", sizeof(pR->restaurant_name) - 1);
		pR->restaurant_name[sizeof(pR->restaurant_name) - 1] = '\0';
		pR->window_count = 0;
		fclose(fp);
		printf("初始化成功\n");
		return;
	}
    fread(pR->restaurant_name, sizeof(char), nameLen, fp);
    pR->restaurant_name[nameLen] = '\0';

    // 读取窗口数量
    fread(&pR->window_count, sizeof(int), 1, fp);

    // 读取所有窗口
    for (int w = 0; w < pR->window_count; w++) {
        Window* win = &pR->windows[w];

        // 读取窗口基本信息
        fread(&win->window_id, sizeof(int), 1, fp);

        int winNameLen;
        fread(&winNameLen, sizeof(int), 1, fp);
        fread(win->window_name, sizeof(char), winNameLen, fp);
        win->window_name[winNameLen] = '\0';

        fread(&win->dish_count, sizeof(int), 1, fp);
        fread(&win->order_count, sizeof(int), 1, fp);
        fread(&win->window_state, sizeof(int), 1, fp);

        // 读取菜品数据
        if (win->dish_count > 0) {
			fread(win->dishes, sizeof(Dish), win->dish_count, fp);
		}
        // 读取订单数据
        if (win->order_count > 0) {
			fread(win->Orders, sizeof(Dish), win->order_count, fp);
		}
    }

    fclose(fp);
    printf("数据加载成功\n");
    return;

}
// 1. 修改餐馆名称（改名功能）
void Restaurant_set_name(Restaurant *pR, const char *new_name){
	if(pR == NULL || new_name == NULL) return;
	strncpy(pR->restaurant_name, new_name, sizeof(pR->restaurant_name) - 1);
	pR->restaurant_name[sizeof(pR->restaurant_name) - 1] = '\0';
}
// 2. 打印餐馆概览（名称、窗口数量、营业窗口数）  
void Restaurant_show_overview(Restaurant *pR){
	if(pR == NULL) return;
	printf("餐厅名称：%s\n", pR->restaurant_name);
	printf("餐厅窗口数量：%d\n", pR->window_count);
	int open_counts = 0;
	for(int i = 0; i < pR->window_count; i++){
		if(pR->windows[i].window_state == 1)
			open_counts++;
	}
	printf("当前营业窗口数：%d\n", open_counts);
}

// 保存数据到文件中
void Restaurant_sava(Restaurant *pR) {
	FILE* fp = fopen("./file.txt", "wb");
    if (!fp) {
        perror("保存文件失败");
        return;
    }
    
    // 写入餐馆名称（带长度前缀）
    int nameLen = strlen(pR->restaurant_name);
    fwrite(&nameLen, sizeof(int), 1, fp);
    fwrite(pR->restaurant_name, sizeof(char), nameLen, fp);
    
    // 写入窗口数量
    fwrite(&pR->window_count, sizeof(int), 1, fp);
    
    // 遍历所有窗口
    for (int w = 0; w < pR->window_count; w++) {
        Window* win = &(pR->windows[w]);
        
        // 写入窗口基本信息
        fwrite(&win->window_id, sizeof(int), 1, fp);
        
        int winNameLen = strlen(win->window_name);
        fwrite(&winNameLen, sizeof(int), 1, fp);
        fwrite(win->window_name, sizeof(char), winNameLen, fp);
        
        fwrite(&win->dish_count, sizeof(int), 1, fp);
        fwrite(&win->order_count, sizeof(int), 1, fp);
        fwrite(&win->window_state, sizeof(int), 1, fp);
        
        // 写入菜品数据
        if (win->dish_count > 0) {
			fwrite(win->dishes, sizeof(Dish), win->dish_count, fp);
		}
        // 写入订单数据
        if (win->order_count > 0) {
			fwrite(win->Orders, sizeof(Dish), win->order_count, fp);
		}

    }
    
    fclose(fp);
    printf("数据保存成功\n");
}

// 16. 统计餐馆总菜品数量 
int Restaurant_calc_total_dishes(Restaurant *pR){
    if(!pR)
        return 0;
    int total_dishes = 0;
    for(int i = 0; i < pR->window_count; i++)
        total_dishes += pR->windows[i].dish_count;
    return total_dishes;
}
// 17. 窗口库存预警（打印该窗口各个菜品的库存数量以及是否库存不足）
int Window_stock_warning(Window *pWin, int threshold){
    int dangours_dish_counts = 0;
    for(int i = 0; i < pWin->dish_count; i++){
        printf("菜品：%s  库存数量为：%d\n", pWin->dishes[i].name, pWin->dishes[i].stock);
        if(pWin->dishes[i].stock < threshold){
            printf("库存数量不足！\n");
            dangours_dish_counts++;
        }
        else
            printf("库存数量充足！\n");
    }
    return dangours_dish_counts;
}

/**
 * @brief 计算整个窗口的收入
 * 
 * 循环遍历窗口中的订单，将订单的价钱加起来
 * 
 * @param pWin 指向该窗口结构体的指针
 * @return float 返回该窗口的营业额
 */
float Window_calc_revenue(Window *pWin) {
	float money = 0;
	for (int i = 0; i < pWin->order_count; i++) {
		money += pWin->Orders[i].price * pWin->Orders[i].stock;
	}
	return money;
}

/**
 * @brief 计算整个餐馆的收入
 * 
 * 循环遍历每个窗口中的订单，将订单的价钱加起来
 * 
 * @param pWin 指向该窗口结构体的指针
 * @return float 返回该窗口的营业额
 */

float Restaurant_Window_calc_revenue(Restaurant * pR){
	int money = 0;
	for (int i = 0; i < pR->window_count; i++) {
		for (int j = 0; j < pR->windows[i].order_count; j++) {
			money += pR->windows[i].Orders[j].price * pR->windows[i].Orders[j].stock;
		}
	}
	return money;
}
//打印所有窗口信息
void printf_all_window_info(Restaurant * pR) {
	if (pR->window_count == 0) {
		printf("当前餐馆暂无窗口！请先添加窗口\n");
		return;
	}
    printf("\n%-10s%-15s%-10s%-10s%-10s\n", 
           "窗口序号", "  窗口名称", "  菜品数", "  订单数", "  状态");
    printf("--------------------------------------------\n");
    for (int i = 0; i < pR->window_count; i++) {
        Window *win = &pR->windows[i];
        printf("%d        %s      %d      %d       %s\n",
               i+1,
               win->window_name,
               win->dish_count,
               win->order_count,
               win->window_state == 1 ? "营业" : "已打烊");
    }
    printf("--------------------------------------------\n");
}	
//打印窗口信息
void printf_window_info(Window *win,int i) {
    printf("\n窗口序号:%d\n窗口名称:%s\n菜品总数:%d\n订单菜品总数:%d\n",
           i, win->window_name, win->dish_count, win->order_count);
}
//查找窗口
int Window_find(Restaurant * pR){
	int choice;
	while (1){
		printf("请根据窗口序号，或窗口名称查找\n1.商品序号\n2.商品名称\n\n请您选择(1 或 2)：");
		scanf("%d",&choice);
		if (1 != choice && 2 != choice){
			printf("请输入有效数字!");
			while (getchar() != '\n');
		}else{
			while (getchar() != '\n');
			break;
		}
	}
	switch (choice){
		case 1:
			{
			int id;
			printf("请输入窗口序号：");
			scanf("%d",&id);
			int i = id-1;
			while (getchar() != '\n');
			if (i < pR->window_count && i >= 0){
				printf_window_info(&pR->windows[i], i+1);
				return i;
				}
			printf("未找到该序号的窗口！\n");
			return -1;
			}
		case 2:
			{
			char name[30];
			printf("请输入窗口名称：");
			scanf("%29s",name);
			while (getchar() != '\n');
			for (int i = 0; i <  pR->window_count; i++){
				if (0 == strcmp(pR->windows[i].window_name, name)){
					printf_window_info(&pR->windows[i], i+1);
					return i;
				}
			}
			printf("未找到 名称为%s 的窗口！\n", name);
			return -1;
			}

	}
}
// 设置窗口营业状态
void Window_set_open(Restaurant *pR){
	printf_all_window_info(pR);
	int id;
	while (1){
		printf("\n您要修改哪个窗口的状态(请输入窗口序号):");
		scanf("%d",&id);
		if (id < 1 || id > pR->window_count){
        	printf("输入无效，请重新输入！\n");
        	while (getchar() != '\n');
		}else{
			break;
		}
	}
	if (1 == pR->windows[id-1].window_state){
		pR->windows[id-1].window_state = 0;
		printf("已将%d号窗口打烊。",id);
	}else{	
		pR->windows[id-1].window_state = 1;
		printf("%d号窗口已开始营业！",id);
	}
}

//批量关闭/开启窗口(如打烊时关闭所有窗口)
void Restaurant_batch_set_window_status(Restaurant *pR){
	if (pR->window_count == 0) {
        printf("当前餐馆暂无窗口！\n");
        return;
    }

    int choice;
    while (1) {
        printf("请选择操作:\n");
        printf("1. 所有窗口打烊\n");
        printf("2. 所有窗口营业\n");
        printf("请输入您的选择(1或2): ");
        scanf("%d", &choice);
        
        if (1 == choice || 2 == choice) {
            break;
        }
        printf("输入无效，请重新输入！\n");
        while (getchar() != '\n');
    }

    int status = (choice == 1) ? 0 : 1;
    for (int i = 0; i < pR->window_count; i++) {
        pR->windows[i].window_state = status;
    }

    printf("已将所有窗口设置为%s状态\n", status ? "营业" : "打烊");
}

